from socket import *
from threading import Thread

HOST = 'localhost'
PORT = 5550
BUFSIZE = 1024
ADDR = (HOST, PORT)

Sock = socket(AF_INET, SOCK_STREAM)

Sock.connect(ADDR)

Sock.send(b'1')
print(Sock.recv(BUFSIZE).decode())
nickname = input("input your nickname:")
Sock.send(nickname.encode())


def sendThreadFunc():
    while True:
        try:
            myword = input(">>>")
            myword = myword.encode('utf-8')
            print(Sock.recv(BUFSIZE).decode())  ##这里先后顺序并没有差别的。
            Sock.send(myword)
        except ConnectionAbortedError:
            print('Warning! The connection is aborted!')
        except ConnectionResetError:
            print("Warning! The connection is reset!")


def recvThreadFunc():
    while True:
        try:
            otherword = Sock.recv(BUFSIZE)
            if otherword:
                print(otherword.decode())
            else:
                pass
        except ConnectionResetError:
            print("Warning! The connection is reset!")
        except ConnectionAbortedError:
            print("Warning! The connection is aborted!")


send1 = Thread(target=sendThreadFunc)
recv1 = Thread(target=recvThreadFunc)
threads = [send1, recv1]

for t in threads:
    t.setDaemon(True)
    t.start()
    t.join()
